package cn.chenc.framework.demo.controller;

import cn.chenc.framework.core.annotation.RepeatSubmit;
import cn.chenc.framework.core.component.AbstractJwtTemplate;
import cn.chenc.framework.core.component.RedisJwtTemplate;
import cn.chenc.framework.core.exception.CustomException;
import cn.chenc.framework.core.model.request.RequestHolder;
import cn.chenc.framework.core.model.response.AjaxResult;
import cn.chenc.framework.core.model.response.CustomCode;
import cn.chenc.framework.demo.entity.User;
import cn.chenc.framework.security.jwt.SecurityJwtTemplate;
import cn.chenc.framework.security.model.SecurityLoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 　@description: TODO
 * 　@author secret
 * 　@date 2021/4/30 14:01
 *
 */
@Controller
public class LoginController {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private AbstractJwtTemplate abstractJwtTemplate;

    @ResponseBody
    @PostMapping("/login")
    public AjaxResult login(@RequestBody User user){
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
        } catch (Exception e) {
            throw new CustomException(CustomCode.error(e.getMessage()));
        }
        //登录成功
        SecurityLoginUser securityLoginUser = (SecurityLoginUser) authentication.getPrincipal();
        String token=abstractJwtTemplate.createToken(securityLoginUser);
        AjaxResult ajax=AjaxResult.success();
        ajax.put("token",token);
        return ajax;
    }

    @RepeatSubmit
    @ResponseBody
    @PostMapping("getInfo")
    public AjaxResult getInfo(@RequestBody User user){
        SecurityLoginUser securityLoginUser = (SecurityLoginUser) abstractJwtTemplate.getLoginUser(RequestHolder.getRequest());
        return AjaxResult.success(securityLoginUser);
    }

    @PreAuthorize("@ss.hasPermi('test')")
    @GetMapping("/test")
    public AjaxResult testPermission(){
        return AjaxResult.success();
    }

}
